package com.xin.di.uav.common.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * 网络Utils
 * Created by 01304522 on 2018/4/11.
 */
public class NetUtils {

    /**
     * 获取本地IP
     * @return
     */
    public static String getLocalHost(){
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return address == null ? "127.0.0.1" : address.getHostAddress();
    }

    /**
     * 获取Linux IP
     * @return
     */
    public static String getLinuxIp() {
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                String name = intf.getName();
                if (!name.contains("docker") && !name.contains("lo")) {
                    for (Enumeration<InetAddress> enumIpAddr = intf
                            .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipaddress = inetAddress.getHostAddress().toString();
                            if (!ipaddress.contains("::")
                                    && !ipaddress.contains("0:0:")
                                    && !ipaddress.contains("fe80")) {
                                ip = ipaddress;
                            }
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            ip = "127.0.0.1";
        }
        return ip;
    }

    public static long negtiveInt2Long(int negtiveInt){
        return negtiveInt&0xffffffffL;
    }

    public static int long2NegtiveInt(long negtiveLong){
        return (int)negtiveLong;
    }

    public static void main(String[] args) {
        System.out.println(NetUtils.negtiveInt2Long(-65259));
        System.out.println(long2NegtiveInt(4293920729L));
    }
}

